﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BAL.PublishSharepoint;
using System.Diagnostics;
using System.Data.SqlClient;
using System.Data;
using DAL.EstRec;
using BAL.EstRec.FDVUtil;

namespace BAL.EstRec
{
    public class PublishFDV
    {
        private ExcelRHQ xls;
        long version;
        XLSActionsProcess xlsProc;
        public List<string> failedXls{get;set;}
        System.Windows.Window wnd;
        bool _isPublish;

        public bool isPublish
        {
            get { return _isPublish; }
        }

        public PublishFDV(long version,System.Windows.Window wnd)
        {
            this.wnd = wnd;
            this.version = version;
            this._isPublish = Convert.ToBoolean(GetPublishStatusVersion(this.version));
            xlsProc = new XLSActionsProcess();
        }//constructor

        public void Publish(VMPublish vm)
        {

            List<string> re = new List<string>();

            if (!this.isPublish)
                re = Recurso.GetRecursoIdxVersion(this.version);    //la versión no ha sido previamente publicada
            else
                re = Recurso.GetRecursostoPublish(this.version);    //la versión ya ha sido previamente publicada 

            xls = new ExcelRHQ(this.version.ToString(), re);//('20120906102424323', new List<string> { "ALIADOSBGT3P", "DINAMICDELV1", "GRAFICOFORV1" });
            xls.xlsCreated += new BAL.EstRec.EventHandler<XLSExportEvents>(xls_xlsCreated);
            xls.xlsCreationError += new BAL.EstRec.EventHandler<XLSExportEvents>(xls_xlsCreationError);
            xls.ExportXLS(vm);
            this.failedXls = xls.failedXls;
            
        }//

        /// <summary>
        /// se usa la primera vez que se publica la versión
        /// </summary>
        /// <param name="e"></param>
        /// <param name="c"></param>
        private void Publish_FDV(XLSExportEvents e, AppConfs c)
        {

            string biblio = e.xlsInfo.recurso.pathPublicacion.Split('/').Last();
            string cntxt = e.xlsInfo.recurso.pathPublicacion.Replace(biblio, "");
            string fName = e.xlsInfo.nombre.Split('\\').Last();//e.xlsInfo.nombre.Split('/').Last();
            string posCode = BAL.EstRec.AUTH.Auth.GetTerritorio();
            string title = fName.Split('.')[0];

            Territorio t = new Territorio(posCode);
            string appr1 = t.supervision;
            string appr2 = t.gerencia;


            try
            {
                PublishSP publish = new PublishSP(cntxt, biblio, fName, e.xlsInfo.nombre, System.Security.Principal.WindowsIdentity.GetCurrent().Name);
                switch (e.xlsInfo.recurso.tipoRecurso)
                {
                    case "TPOSM":

                        publish.PublishTPOSM(title, posCode, e.xlsInfo.iniciativa, e.xlsInfo.totalPos.ToString(), e.xlsInfo.tiempoImplement.ToString());
                        // se copia a la carpeta compartida
                        System.IO.File.Copy(e.xlsInfo.nombre, c.cnf.SharedFolderFDV + fName);
                        break;
                    case "REA":
                        publish.PublishREA(title, posCode, e.xlsInfo.totalPos.ToString(), e.xlsInfo.tiempoImplement.ToString(), appr1);
                        break;
                    case "CEA":
                        publish.PublishCEA(title, posCode, e.xlsInfo.totalPos.ToString(), e.xlsInfo.tiempoImplement.ToString(), appr1, appr2);
                        break;

                    default:
                        break;
                }

                FdvVersion.UpdateFlagToPublish(long.Parse(fName.Split('_')[0]), fName.Split('_')[1], false);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }//

        

        /// <summary>
        /// Consulta si la versión ya ha sido publicada 
        /// </summary>
        /// <param name="unidVersion">Verisón de la cual hará consulta</param>
        /// <returns>1 si ya ha sido publicada; 0 de lo contrario</returns>
        public int GetPublishStatusVersion(long unidVersion)
        {
            SqlCommand cmd = new SqlCommand("SP_ER_GET_ISVERSIONPUBLISHED");
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.Add(new SqlParameter("@UNID_VERSION", unidVersion));
            DataSet ds = new DataSet();
            int isPublished = 0;

            try
            {
                ds = SrvDB.ExecuteCommand(cmd);
                if (ds.Tables.Count > 0)
                    if (ds.Tables[0].Rows.Count > 0)
                        isPublished = int.Parse(ds.Tables[0].Rows[0]["IS_PUBLISHED"].ToString());
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            return isPublished;
        }//

        //Evento de error en la creación de archivo excel
        void xls_xlsCreationError(object sender, XLSExportEvents e)
        {
            Console.WriteLine("Error en la creación de  " + e.xlsInfo.nombre+"\n"+e.xlsInfo.msg);
            
        }//

        //evento de creación exitosa de archivo excel
        void xls_xlsCreated(object sender, XLSExportEvents e)
        {
            Console.WriteLine(e.xlsInfo.nombre + " creado.");

            /** 20121207
            // mata al proceso de Excel
            xlsProc.KillExcel();

            AppConfs c = new AppConfs();
            // Publica en WorkPoint
           Publish_FDV(e, c);
             * */
            //-------------------------------- 2012-12-06

            AppConfs c = new AppConfs();

            //obtiene el número de intentos de creación 
            int numTry = 0;
            int.TryParse(c.cnf.NumTryCreateXls, out numTry);
            int currentTry = 0;

            do
            {
                try
                {
                    // mata al proceso de Excel
                    this.xlsProc = new XLSActionsProcess();
                    if (this.xlsProc.isExcelActive)
                        this.xlsProc.KillExcel();

                    // Publica en WorkPoint
                   Publish_FDV(e, c);

                    numTry = 0;
                }
                catch (Exception exx)
                {
                    numTry--;
                    currentTry++;
                    Console.WriteLine("Intento: " + currentTry + " fallido.");

                    this.xlsProc = new XLSActionsProcess();

                    if (this.xlsProc.isExcelActive)
                        this.xlsProc.KillExcel();


                    if (numTry == 0)
                        throw new Exception("No se pudo finalizar la creación del archivo Excel." + exx.Message + ". Intentos: " + currentTry.ToString());
                }

            } while (numTry > 0);

            

        }//

    }// end class
}
